import com.gskinner.ui.DisplayObjectWrapper;
import com.smartfoxserver.v2.SmartFox;
import com.smartfoxserver.v2.core.SFSEvent;
import com.smartfoxserver.v2.entities.Room;
import com.smartfoxserver.v2.requests.CreateRoomRequest;
import com.smartfoxserver.v2.requests.ExtensionRequest;
import com.smartfoxserver.v2.requests.JoinRoomRequest;
import com.smartfoxserver.v2.requests.RoomExtension;
import com.smartfoxserver.v2.requests.SubscribeRoomGroupRequest;
import com.smartfoxserver.v2.requests.game.SFSGameSettings;
import com.smartfoxserver.v2.util.ClientDisconnectionReason;
import com.smartfoxserver.v2.entities.data.SFSObject;

import components.CreateGamePanel;
import components.GameMessage;

import flash.events.Event;
import flash.net.*;
import flash.net.URLRequest;

import mx.controls.Alert;
import mx.events.CloseEvent;
import mx.managers.PopUpManager;

import unipampa.games.pampaPife.PampaPifeGame;

private var jogoVisaoIniciada:Boolean;
private var sfs:SmartFox;
private var alert:Alert;
private var createGamePanel:CreateGamePanel;
private var gameInstance:PampaPifeGame;
private var gameMessage:GameMessage;

private const THE_LOBBY_NAME:String = "The Lobby";
private const GAME_ROOMS_GROUP_NAME:String = "games";
private const EXTENSION_ID:String = "PampaPife";
private const EXTENSIONS_CLASS:String = "unipampa.extensions.games.pampaPife.PampaPifeExtension";

private function  init():void{
	jogoVisaoIniciada = false;
	
	// Get reference to SmartFoxServer connection
	sfs = loginPanel.connector.connection;
	sfs.addEventListener(SFSEvent.LOGIN, onLogin);
	sfs.addEventListener(SFSEvent.CONNECTION_LOST, onConnectionLost);
	/*	sfs.addEventListener(SFSEvent.ROOM_CREATION_ERROR, onRoomCreationError);  */
	sfs.addEventListener(SFSEvent.ROOM_JOIN, onRoomJoin);
	/*	sfs.addEventListener(SFSEvent.ROOM_JOIN_ERROR, onRoomJoinError);
	*/	
	// Create game creation panel instance
	createGamePanel = new CreateGamePanel();
	createGamePanel.addEventListener(CloseEvent.CLOSE, onCreatePopUpClosed);
	createGamePanel.initialize();
}

/**============================================================================
 * SFS Event Handlers - Tratando eventos do SFS
 * */
private function onLogin(evt:SFSEvent):void{ // Quando o usuario faz login
	// Check if the "game" group is already subscribed;
	// if not, subscribe it
	if (!sfs.roomManager.containsGroup(GAME_ROOMS_GROUP_NAME))
		sfs.send(new SubscribeRoomGroupRequest(GAME_ROOMS_GROUP_NAME));

	// Move to chat view, and display user name 
	mainView.selectedChild = view_lobby;
	lb_myUserName.text = sfs.mySelf.name;
}
private function onRoomJoin(evt:SFSEvent):void{ // Quando usuario entre em uma sala
	var room:Room = evt.params.room;
	
	if (room.name == THE_LOBBY_NAME){
		// Show lobby view
		mainView.selectedChild = view_lobby;
	}
	else{
		
		var urlreq:URLRequest = new URLRequest("http://192.168.9.1/chat3/user.php");
		var loaderUrl:URLLoader = new URLLoader();
		var varLoader:URLVariables = new URLVariables();
		
		varLoader.login = sfs.mySelf.name;
		varLoader.sala = sfs.lastJoinedRoom.id;
		urlreq.method = URLRequestMethod.POST;
		urlreq.data = varLoader;
		loaderUrl.load(urlreq);
		
		// Go to game view
		mainView.selectedChild = view_game;
		
		// Initialize game
		initGame();
	}
}
private function onConnectionLost(evt:SFSEvent):void{ // Quando perde a conexão com o servidor (enviado pelo servidor)
	// Destroy game instance, if any
	destroyGame();
	
	// Remove popup, if any
	removeCreatePopUp();
	
	// Remove alert, if displayed
	removeAlert();
	
	// Show disconnection message, unless user chose voluntarily to close the connection
	if (evt.params.reason != ClientDisconnectionReason.MANUAL)
	{
		var msg:String = "Connection lost";
		
		switch (evt.params.reason)
		{
			case ClientDisconnectionReason.IDLE:
				msg += "\nYou have exceeded the maximum user idle time";
				break;
			
			case ClientDisconnectionReason.KICK:
				msg += "\nYou have been kicked";
				break;
			
			case ClientDisconnectionReason.BAN:
				msg += "\nYou have been banned";
				break;
			
			case ClientDisconnectionReason.UNKNOWN:
				msg += " due to unknown reason\nPlease check the server-side log";
				break;
		}
		
		loginPanel.ta_error.text = msg;
	}
	
	// Show login view
	mainView.selectedChild = view_connecting;
}

/**============================================================================
 * Criando nova Sala de Jogo
 * */
private function onCreateGameApplicationBtClick():void{ // Evento do Botão "Nova sala"
	createGamePanel.reset();
	PopUpManager.addPopUp(createGamePanel, this, true);
	PopUpManager.centerPopUp(createGamePanel);
}
public function onCreateGamePopuUpBtClick():void{ // Evento da criacao da sala
	if (createGamePanel.ti_name.length > 0)	{
		// Create game settings
		var settings:SFSGameSettings = new SFSGameSettings(createGamePanel.ti_name.text);
		settings.groupId = GAME_ROOMS_GROUP_NAME;
		settings.password = createGamePanel.ti_password.text;
		settings.isGame = true;
		settings.maxUsers = 10;
		settings.maxSpectators = createGamePanel.ns_maxSpectators.value;
		
		settings.extension = new RoomExtension(EXTENSION_ID, EXTENSIONS_CLASS);
		
		// Create room
		var request:CreateRoomRequest = new CreateRoomRequest(settings, true, sfs.lastJoinedRoom);
		sfs.send(request);
		
		// Close popup
		removeCreatePopUp();
	}
}
public function removeCreatePopUp():void{ // Remove a janela de criacao de sala
	PopUpManager.removePopUp(createGamePanel);
}
private function onCreatePopUpClosed(evt:Event):void{ // Removendo pop up 
	removeCreatePopUp();
}

/**============================================================================
 * Métodos do Jogo
 * */
private function initGame():void{
	if (!jogoVisaoIniciada)
		jogoVisaoIniciada = true;
	
	gameInstance = new PampaPifeGame();
	
	var dow:DisplayObjectWrapper = new DisplayObjectWrapper();
	dow.content = gameInstance;
	gameContainer.addChild(dow);
	
	var params:Object = {};
	params.sfs = sfs;
	params.container = this;
	
	gameInstance.initGame(params);
}

private function destroyGame():void{
	if (gameInstance != null){
		var dow:DisplayObjectWrapper = gameContainer.getChildAt(0) as DisplayObjectWrapper;
		dow.content = null;
		gameContainer.removeChild(dow);
		
		gameInstance.destroyGame();
		gameInstance = null;
	}
	
	// Remove game message, if any
	removeGamePopUp();
}
/**============================================================================
 * Outros
 * */
private function onLeaveGameBtClick():void{ // Evento do Botão Deixar Jogo
	var request:JoinRoomRequest = new JoinRoomRequest(THE_LOBBY_NAME, null, sfs.lastJoinedRoom.id);
	sfs.send(new ExtensionRequest("deixarJogo", new SFSObject(), sfs.lastJoinedRoom ) );
	sfs.send(request);
	// Destroy game instance
	destroyGame();
}
public function showGamePopUp(type:String, msg:String, callback:Function):void{
	// Remove previous popup if any
	removeGamePopUp();
	
	// Display game message
	gameMessage = PopUpManager.createPopUp(gameContainer, GameMessage, false) as GameMessage;
	gameMessage.currentState = type;
	gameMessage.message = msg;
	gameMessage.callBack = callback;
	
	// Disable board
	gameContainer.enabled = false;
}	

public function removeGamePopUp():void{
	// Remove game message
	PopUpManager.removePopUp(gameMessage);
	
	// Enable board
	gameContainer.enabled = true;
}

private function removeAlert():void{
	if (alert != null)
		PopUpManager.removePopUp(alert);
	
	alert = null;
}
